import React, { useState, useEffect } from 'react';
import './index.css';
import { getBookmarks, categorizeBookmarks } from '../utils/bookmarkUtils';
import { Bookmark, Category, CategoryStats } from '../types';
import SearchBar from './components/SearchBar';
import FilterBar from './components/FilterBar';
import ViewToggle from './components/ViewToggle';
import BookmarkGrid from './components/BookmarkGrid';
import NetworkGraph from './components/NetworkGraph';

const App: React.FC = () => {
  const [bookmarks, setBookmarks] = useState<Bookmark[]>([]);
  const [filteredBookmarks, setFilteredBookmarks] = useState<Bookmark[]>([]);
  const [categories, setCategories] = useState<Category[]>([]);
  const [selectedCategories, setSelectedCategories] = useState<string[]>([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [currentView, setCurrentView] = useState<'card' | 'graph'>('card');
  const [bookmarkCount, setBookmarkCount] = useState(0);
  const [categoryStats, setCategoryStats] = useState<CategoryStats[]>([]);

  // 加载书签和分类
  useEffect(() => {
    const fetchData = async () => {
      try {
        setIsLoading(true);
        const rawBookmarks = await getBookmarks();
        const { categorizedBookmarks, allCategories } = await categorizeBookmarks(rawBookmarks);
        
        setBookmarks(categorizedBookmarks);
        setFilteredBookmarks(categorizedBookmarks);
        setCategories(allCategories);
        setBookmarkCount(categorizedBookmarks.length);
        
        // 生成分类统计
        setCategoryStats(getCategoryStats(categorizedBookmarks, allCategories));
        
        setIsLoading(false);
      } catch (err) {
        setError('加载书签时出错: ' + (err instanceof Error ? err.message : String(err)));
        setIsLoading(false);
      }
    };

    fetchData();
  }, []);

  // 计算分类统计
  const getCategoryStats = (bookmarks: Bookmark[], categories: Category[]): CategoryStats[] => {
    const stats: Record<string, number> = {};
    
    // 初始化统计
    categories.forEach(cat => {
      stats[cat.id] = 0;
    });
    
    // 计数每个分类的书签数量
    bookmarks.forEach(bookmark => {
      if (bookmark.categoryId && stats[bookmark.categoryId] !== undefined) {
        stats[bookmark.categoryId]++;
      }
    });
    
    // 转换为CategoryStats数组
    return categories.map(cat => ({
      id: cat.id,
      count: stats[cat.id] || 0,
      percentage: bookmarks.length > 0 ? (stats[cat.id] / bookmarks.length) * 100 : 0
    }));
  };

  // 过滤书签
  useEffect(() => {
    let result = [...bookmarks];
    
    // 按搜索词过滤
    if (searchTerm) {
      const term = searchTerm.toLowerCase();
      result = result.filter(bookmark => 
        bookmark.title.toLowerCase().includes(term) || 
        bookmark.url.toLowerCase().includes(term)
      );
    }
    
    // 按分类过滤
    if (selectedCategories.length > 0) {
      result = result.filter(bookmark => 
        selectedCategories.includes(bookmark.categoryId)
      );
    }
    
    setFilteredBookmarks(result);
  }, [searchTerm, selectedCategories, bookmarks]);

  // 处理搜索
  const handleSearch = (term: string) => {
    setSearchTerm(term);
  };

  // 处理分类筛选
  const handleCategoryFilter = (categories: string[]) => {
    setSelectedCategories(categories);
  };

  // 处理视图切换
  const handleViewChange = (view: 'card' | 'graph') => {
    setCurrentView(view);
  };

  // 清除所有筛选
  const clearFilters = () => {
    setSearchTerm('');
    setSelectedCategories([]);
  };

  return (
    <div className="app-container min-h-screen bg-gray-50">
      <header className="bg-white border-b border-gray-200 shadow-sm sticky top-0 z-10">
        <div className="container mx-auto px-4 py-3">
          <div className="flex flex-col md:flex-row items-center justify-between gap-4">
            <div className="flex items-center">
              <img src="/icons/icon48.png" alt="BookmarkVision Logo" className="w-8 h-8 mr-2" />
              <h1 className="text-xl font-semibold text-gray-800">书签视界</h1>
              {!isLoading && (
                <span className="ml-2 text-sm text-gray-500">
                  {bookmarkCount} 个书签
                </span>
              )}
            </div>
            
            <div className="flex flex-1 md:flex-none items-center space-x-2 w-full md:w-auto">
              <SearchBar searchTerm={searchTerm} onSearch={handleSearch} />
              <ViewToggle currentView={currentView} onViewChange={handleViewChange} />
            </div>
          </div>
        </div>
      </header>

      <main className="container mx-auto px-4 py-6">
        {isLoading ? (
          <div className="flex justify-center items-center h-64">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500"></div>
          </div>
        ) : error ? (
          <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-md">
            <p className="font-medium">加载出错</p>
            <p className="text-sm">{error}</p>
            <button 
              className="mt-2 px-4 py-2 bg-red-100 hover:bg-red-200 text-red-700 rounded-md text-sm transition-colors duration-200"
              onClick={() => window.location.reload()}
            >
              重试
            </button>
          </div>
        ) : (
          <>
            <div className="mb-6">
              <FilterBar 
                categories={categories} 
                selectedCategories={selectedCategories} 
                onCategorySelect={handleCategoryFilter}
                categoryStats={categoryStats}
              />
            </div>
            
            {filteredBookmarks.length === 0 && (searchTerm || selectedCategories.length > 0) ? (
              <div className="flex flex-col items-center justify-center h-64 text-gray-500">
                <svg xmlns="http://www.w3.org/2000/svg" className="h-16 w-16 mb-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1} d="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
                <p>没有符合条件的书签</p>
                <button 
                  onClick={clearFilters}
                  className="mt-4 px-4 py-2 bg-blue-100 hover:bg-blue-200 text-blue-700 rounded-md text-sm transition-colors duration-200"
                >
                  清除筛选条件
                </button>
              </div>
            ) : (
              currentView === 'card' ? (
                <BookmarkGrid 
                  bookmarks={filteredBookmarks} 
                  categories={categories}
                  loading={isLoading}
                />
              ) : (
                <NetworkGraph 
                  bookmarks={filteredBookmarks}
                  categories={categories}
                />
              )
            )}
          </>
        )}
      </main>

      <footer className="mt-auto py-4 text-center text-gray-500 text-sm">
        <p>BookmarkVision © {new Date().getFullYear()}</p>
      </footer>
    </div>
  );
};

export default App; 